package controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import bean.Fund;
import bean.Model;
import bean.UserType;
import dao.FundDAO;
import formBean.CreateFundForm;

public class CreateFundAction extends Action {
	private FormBeanFactory<CreateFundForm> formBeanFactory = FormBeanFactory.getInstance(CreateFundForm.class);
	private FundDAO fundDAO;
	
	public CreateFundAction(Model model) {
		this.fundDAO = model.getFundDAO();
	}

	@Override
	public String getName() {
		return "createFund.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		ArrayList<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		
		try {
			CreateFundForm form = formBeanFactory.create(request);
			request.setAttribute("form", form);
			
			if (!form.isPresent()) {
				return "createFund.jsp";
			}
			
			errors.addAll(form.getValidationErrors());
			
			if (errors.size() > 0) {
				return "createFund.jsp";
			}
			
			Fund f = fundDAO.getFundByName(form.getFundname());
			
			if (f != null) {
				errors.add("The fund name already exists.");				
			}
			
			f = fundDAO.getFundBySymbol(form.getTicker());
			
			if (f != null) {
				errors.add("The fund symbol already exists.");				
			}
			
			if (errors.size() > 0) return "createFund.jsp";
			
			Fund fund = new Fund();
			fund.setName(form.getFundname());
			fund.setSymbol(form.getTicker());
			if (fundDAO.createFund(fund)) {			
				request.setAttribute("message", "You have successfully created fund " + fund.getName() + " (" + fund.getSymbol() + ").");
				return "employeeConsole.jsp";
			}
			
			errors.add("The operation cannot be executed. Please contact the admin.");	
			return "createFund.jsp";
		} catch (FormBeanException e) {
			e.printStackTrace();
			errors.add(e.getMessage());
			return "createFund.jsp";
		}		
	}

	@Override
	public UserType getType() {
		return UserType.Employee;
	}
}
